<?php
namespace app\controller;

use app\BaseController;
use \think\facade\Request;
use app\command\ComModel;
use \think\facade\Cache;
use \think\facade\Db;
use \think\facade\Log;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Credentials\Credential;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
// use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\Dara\Models\RuntimeOptions;
use EasyWeChat\Kernel\Support;


class Api extends BaseController
{
    
    public static function createClient(){
        $config = new Config([
			'accessKeyId' => 'LTAI5t9oiZEKnEMpBp5WdP4Y',
			'accessKeySecret' => 'LmoRZtrUDfBHFXoZ6GV7vFyGoHPyHd',
		]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
        
    }
    public function sendMsg(){
		$params = Request::param();
		$order_id = $params['order_id'];
		$order_info = Db::name('order_info')
				->field('user_id,goods_name,num,spec')
				->where('id',$order_id)
				->find();
		$address = $params['address'];
		if(!$order_info){
			return $this->returnJson(400,'订单不存在',[]);
		}

		$user_info = Db::name('users')
				->field('nick_name,phone')
				->where('id',$order_info['user_id'])
				->find();
		if(!$user_info){
			return $this->returnJson(400,'用户不存在',[]);
		}
		if(!$user_info['phone']){
			return $this->returnJson(400,'用户手机号不存在',[]);
		}
		
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $user_info['phone'],
            "signName" => "周口市豫隆酒业",
            "templateCode" => "SMS_498075551",
            "templateParam" => json_encode([   // 模板参数（与模板内容中的${变量}对应）
				"nick_name" => $user_info['nick_name'], // 随机验证码
				'goods_name' => $order_info['goods_name'].$order_info['spec'].'x'.$order_info['num'],
				'address'=>$address,
			]),

        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            return $this->returnJson(200,'发送成功',$res);
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            var_dump($error->data["Recommend"]);
            // Utils::assertAsString($error->message);
        }
    }
    // 使用快递e100查询物流
	public function getLogisticsInfo()
	{
		$param = Request::post();
		if(!$param['deliveryCode']){
			return $this->returnJson(400,'请输入快递单号',[]);
		}

		$logistics_info = getLogisticsInfo($param['deliveryCode']);
		return $this->returnJson(200,'',$logistics_info);
	}
  //获取用户手机号
	public function getUserPhone()
	{
		$param = Request::post();
		$code = $param['code'];
		$user_id = $this->getUserId();
		
		$app = $this->getEasyWeChatMiniProgram();
		$user_phone_info = $app->phone_number->getUserPhoneNumber($code);
		if ($user_phone_info['errcode'] == 0) {
			$phone = $user_phone_info['phone_info']['purePhoneNumber'];
			Db::name('users')
    		  ->where('id',$user_id)
    		  ->update([
    		        'phone'=>$phone
    		      ]);
		   return $this->returnJson(200,'手机号授权成功',['phone'=>$phone]);
		}
 
		return $this->returnJson(400,'手机号授权失败：' . $user_phone_info['errmsg'],[]);
	}
    // 小程序授权登录
  public function wxlogin()
  {
  	
  	$param = Request::param();
  	$code = $param['code'];
  	$app = $this->getEasyWeChatMiniProgram();
  	$res =  $app->auth->session($code);
  	
	// 启动事务
	Db::startTrans();
	try {
		 $user_info =  Db::table('users')
		 	            ->where('openid',$res['openid'])
		 	            ->find();
		  if(!$user_info){
		      $dd1 = [
		            "openid"=>$res['openid'],
		            'add_time'=>date("Y-m-d H:i:s"),
		            'update_time'=>date("Y-m-d H:i:s"),
		        ];
				$id = Db::table('users')->insertGetId($dd1);
				
		  }else{
		      $id = $user_info['id'];
		  }
		  
          if(isset($param['role'])){
             Db::table('users')
             ->where('id',$id)
             ->update(['role'=>$param['role']]);
          }

		  $redis = Cache::store('redis');
		  $token = bin2hex(random_bytes(32));
		  $redis->set($token, $id,36000);
		 
		  $dd = [
		     "openid"=>$res['openid'],
		     "token"=>$token
          ];	 
		 return $this->returnJson(200,'登陆成功',$dd);
		Db::commit();
	} catch (\Exception $e) {
		return $this->returnJson(400,'',$e->getMessage());
		// 回滚事务
		Db::rollback();
	}
  }
  // 获取合作商积分
  public function getHzsPoint()
  {
	$param = Request::param();
  	$user_id = $this->getUserId();
	$point = Db::table('point_water_hzs')
		->where('user_id',$user_id)
		->sum('points');
	// 修改合作商积分
	Db::table('users')
        ->where('id',$user_id)
        ->update(['point'=>$point]);
	return $this->returnJson(200,'操作成功',['point'=>$point]);
  }
  // 获取用户信息
  public function getUserInfo()
  {
  	$param = Request::param();
  	$user_id = $this->getUserId();
    
	$point = Db::table('point_water')
		->where('user_id',$user_id)
		->sum('points');
    // 修改用户积分
    Db::table('users')
        ->where('id',$user_id)
        ->update(['point'=>$point]);

	// 累计奖金
	$total_price = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->where('type','1')
        ->whereNull('delete_time')
        ->sum('reward_price');
	// 可提现金额
	$tixian_price = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->whereNull('delete_time')
        ->sum('reward_price');
	
    
  	$res = Db::table('users')
  		->field('id,age,province,city,area,avatar,role,point,openid,nick_name,phone')
  		->where('id',$user_id)
  		->find();
	$res['total_price'] = $total_price;
	$res['tixian_price'] = $tixian_price;
	
  	$this->returnJson(200,'操作成功',$res);
  }
  // 修改用户信息
  public function updateUserInfo()
  {
  	$param = Request::param();
  	$user_id = $this->getUserId();
	if(isset($param['point'])){
		return $this->returnJson(400,'积分不能修改',[]);
	}
	if(isset($param['openid'])){
		return $this->returnJson(400,'openid不能修改',[]);
	}
	if(isset($param['role'])){
		return $this->returnJson(400,'角色不能修改',[]);
	}
  	$res = Db::table('users')
  		->where('id',$user_id)
  		->update($param);
  	$this->returnJson(200,'操作成功',$res);
  }
  // 二维码核销
  public function qrcodeCheck()
  {
  	try {
	  	$param = Request::param();
	  	$user_id = $this->getUserId();
	    $qr_sn = $param['qr_sn'];
	    $role = Db::table('users')
	        ->field('role')
	        ->where('id',$user_id)
	        ->value('role');

		// 如果 $qr_sn 不在 qrcode_p 表中 也不在qrcode表中 返回二维码有误
		$count = Db::table('qrcode_p')
	        ->where('qr_sn',$qr_sn)
	        ->count();
		if($count == 0){
			$count = Db::table('qrcode')
	        ->where('qr_sn',$qr_sn)
	        ->count();
			if($count == 0){
				Db::rollback();
				return $this->returnJson(400,'二维码有误',[]);
			}
		}
		
		
	    // 1=普通用户,2=合作方,3=业务员 下边代码逻辑比较多加上事务
		Db::startTrans();
		
		if($role == 1){
			$count1 = Db::table('qrcode_p')
	        ->where('qr_sn',$qr_sn)
	        ->count();
			
			if($count1 != 0){
				Db::rollback();
				return $this->returnJson(400,'普通用户不能扫描箱码',[]);
			}
			$arr = ComModel::checkCode1($qr_sn,$user_id);
			Db::commit();
			return $this->returnJson(200,'操作成功',$arr);
		}
		if($role == 2){
			$count2 = Db::table('qrcode')
	        ->where('qr_sn',$qr_sn)
	        ->count();
			
			if($count2 != 0){
				Db::rollback();
				return $this->returnJson(400,'合作方不能扫描瓶码',[]);
			}
			$arr = ComModel::checkCode2($qr_sn,$user_id);
			Db::commit();
			return $this->returnJson(200,'操作成功',$arr);
		}
		if($role == 3){
			$count3 = Db::table('qrcode')
	        ->where('qr_sn',$qr_sn)
	        ->count();
			
			if($count3 != 0){
				Db::rollback();
				return $this->returnJson(400,'业务员不能扫描瓶码',[]);
			}
			$arr = ComModel::checkCode3($qr_sn,$user_id);
			Db::commit();
			return $this->returnJson(200,'操作成功',$arr);
		}
		
		// 如果没有匹配的角色
		Db::rollback();
		return $this->returnJson(403,'无权限操作',[]);
	} catch (\Exception $e) {
		// 发生异常时回滚事务
		Db::rollback();
		return $this->returnJson(500,'系统错误: ' . $e->getMessage(),[]);
	}
  }
  
  // 合作商申请提现
  public function hzfApply()
  {
  	$param = Request::param();
	// 取绝对值
	$price = abs($param['price']);
  	$user_id = $this->getUserId();
    // 	 合作商可提现金额
    $tixian_price = Db::table('reward_history')
        ->where('user_id',$user_id)
		->whereNull('delete_time')
        ->sum('reward_price');
	if($tixian_price < $price){
		return $this->returnJson(400,'可提现金额不足',[]);
	}
	// 插入提现申请表
	$id = Db::table('reward_history')
		->insertGetId([
			'user_id' => $user_id,
			'add_time' => date("Y-m-d H:i:s"),
			'reward_price' => -$price,
			'type' => '2',
			'status' => '0',
			'qr_sn'=>createOrderSn(),
		]);
	if($id){
		return $this->returnJson(200,'提现申请成功',['id'=>$id]);
	}else{
		return $this->returnJson(400,'提现申请失败',[]);
	}


  }
  // 取消本次提现
  public function hzfCancel()
  {
  	$param = Request::param();
  	$id = $param['id'];
  	// reward_history 如果 status=1 不能取消  取消就是软删除本条记录
	$status = Db::table('reward_history')
        ->field('status')
        ->where('id',$id)
        ->value('status');
	if($status == 1){
		return $this->returnJson(400,'业务员已核销不能取消',[]);
	}
	// 软删除
	 $res =  Db::name('reward_history')
                ->where('id',$id)
                ->useSoftDelete('delete_time',time())
                ->delete();
	if($res){
		return $this->returnJson(200,'取消成功',[]);
	}
  }
  // 获取提现记录
  public function getWithdrawApply()
  {
	// 加上分页
	$param = Request::param();
	$page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;

  	$user_id = $this->getUserId();
  	$res = Db::table('reward_history')
  		->where('user_id',$user_id)
		->order('id','desc')
  		->where('type','2')
		->limit($page,$pageSize)
		->whereNull('delete_time')
  		->select();
	$count = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->where('type','2')
        ->whereNull('delete_time')
        ->count();
	// 累计奖金
	$total_price = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->where('type','1')
        ->whereNull('delete_time')
        ->sum('reward_price');
	// 可提现金额
	$tixian_price = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->whereNull('delete_time')
        ->sum('reward_price');
	$dd = [
            'result'=>$res,
            'count'=>$count,
            'total_price'=>$total_price,
            'tixian_price'=>$tixian_price
        ];
     return   $this->returnJson(200,'操作成功',$dd);
  }
  // 业务员扫码
  public function yewuCheck()
  {
	$param = Request::param();
    $id = $param['id'];
    $res = Db::table('reward_history')
		->field('id,qr_sn,user_id,reward_price')
        ->where('id',$id)
        ->whereNull('delete_time')
        ->find();
	
	$user_id = $res['user_id'];
    // 查询用户的 nick_name phone  地址 
    $user = Db::table('users')
        ->field('nick_name,phone,province,city,area,address_info')
        ->where('id',$user_id)
        ->find();
    $res['nick_name'] = $user['nick_name'];
    $res['phone'] = $user['phone'];
    $res['province'] = $user['province'];
    $res['city'] = $user['city'];
    $res['area'] = $user['area'];
    $res['address_info'] = $user['address_info'];
	$res['reward_price'] = abs($res['reward_price']);

	// 可提现金额
	$tixian_price = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->whereNull('delete_time')
        ->sum('reward_price');
	$res['tixian_price'] = $tixian_price; 

    return $this->returnJson(200,'操作成功',$res);
  }
  // 业务员通过申请并发放
  public function passApply()
  {
	$param = Request::param();
	$id = $param['id'];
	$user_id = $this->getUserId();
	// 检查是否是业务员
	$role = Db::table('users')
        ->field('role')
        ->where('id',$user_id)
        ->value('role');
	if($role != 3){
		return $this->returnJson(400,'您不是业务员',[]);
	}
	// 修改 reward_history s_user_id 为user_id  hx_time 当前时间 status 为1
	$res = Db::table('reward_history')
		->where('id',$id)
		->update([
			's_user_id'=>$user_id,
			'hx_time'=>date("Y-m-d H:i:s"),
			'status'=>'1',
		]);
	if($res){
		return $this->returnJson(200,'操作成功',[]);
	}else{
		return $this->returnJson(400,'操作失败',[]);
	}
  }
  // 业务员核销记录
  public function getCheckRecord()
  {
	// 加上分页
	$param = Request::param();
	$page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;

  	$user_id = $this->getUserId();
  	$res = Db::table('write_off_history')
  		->where('user_id',$user_id)
		->order('id','desc')
		->limit($page,$pageSize)
		->whereNull('delete_time')
  		->select();
	$count = Db::table('write_off_history')
        ->where('user_id',$user_id)
        ->whereNull('delete_time')
        ->count();
     return   $this->returnJson(200,'操作成功',
        [
            'result'=>$res,
            'count'=>$count,
        ]
    );

  }
  // 合作商提现记录 
  public function getCooperationWithdrawApply()
  {
	// 加上分页
	$param = Request::param();
	$page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;

  	$user_id = $this->getUserId();
  	$res = Db::table('reward_history')
  		->where('s_user_id',$user_id)
		->order('id','desc')
  		->where('type','2')
		->limit($page,$pageSize)
		->whereNull('delete_time')
  		->select()
		->all();
    foreach($res as $k=>$v){
        // $v 里边的user_id 的nick_name phone 省市区 地址
		$user = Db::table('users')
        ->field('nick_name,phone,province,city,area,address_info')
        ->where('id',$v['user_id'])
        ->find();
		$res[$k]['nick_name'] = $user['nick_name'];
		$res[$k]['phone'] = $user['phone'];
		$res[$k]['province'] = $user['province'];
		$res[$k]['city'] = $user['city'];
		$res[$k]['area'] = $user['area'];
		$res[$k]['address_info'] = $user['address_info'];
    }	

	$count = Db::table('reward_history')
        ->where('s_user_id',$user_id)
        ->where('type','2')
        ->whereNull('delete_time')
        ->count();
     return   $this->returnJson(200,'操作成功',
        [
            'result'=>$res,
            'count'=>$count,
        ]
    );
  }
  // 获取描述
  public function getDesc()
  {
		$res = Db::table('reward_desc')
		->where('cid',1)
		->find();
		return $this->returnJson(200,'操作成功',$res);
  }
  // 获取合作方扫码结果 
  public function getCooperationScanResult()
  {
	$param = Request::param();
	$aid = $param['aid'];
	$res = Db::table('reward_desc')
		->where('cid',1)
		->find();
	$user_id = $this->getUserId();
	// 获取当前累计奖励
	$total_price = Db::table('reward_history')
        ->where('user_id',$user_id)
		->where('type','1')
        ->whereNull('delete_time')
        ->sum('reward_price');
	// 获取可提现金额
	$tixian_price = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->whereNull('delete_time')
        ->sum('reward_price');
	$res['tixian_price'] = $tixian_price;
	$res['total_price'] = $total_price;
	return $this->returnJson(200,'操作成功',$res);
  }
  // 合作商奖励金额领取记录
  public function getRewardRecord()
  {
	// 加上分页
	$param = Request::param();
	$page=$param['page'];
    $pageSize = $param['pageSize'];
    $page=($page-1)*$pageSize;

  	$user_id = $this->getUserId();
  	$res = Db::table('reward_history')
  		->where('user_id',$user_id)
		->order('id','desc')
		->where('type','1')
		->limit($page,$pageSize)
		->whereNull('delete_time')
  		->select();
	$count = Db::table('reward_history')
        ->where('user_id',$user_id)
        ->where('type','1')
        ->whereNull('delete_time')
        ->count();
     return   $this->returnJson(200,'操作成功',
        [
            'result'=>$res,
            'count'=>$count,
        ]
    );
  }
  // 用户获取中奖奖品
  public function getAwardResult()
  {
	$param = Request::param();
	$aid = $param['aid'];
	$res = Db::table('award_history')
		->where('id',$aid)
		->whereNull('delete_time')
		->find();
	// 奖品id
	$item = Db::table('award')->where('id',$res['aid'])->find();	
	$res['name'] = $item['name'];
	$res['desc'] = $item['desc'];
	$res['image'] = $item['image'];
	return $this->returnJson(200,'操作成功',$res);
  }
  // 添加修改配送地址
  public function addEditDeliveryAddress()
  {
	$param = Request::param();
	$user_id = $this->getUserId();
	// name phone address_info user_id add_time update_time
	if(isset($param['id']) && $param['id']){
		// 修改
		$id = $param['id'];
		$param['update_time'] = date("Y-m-d H:i:s");
		$res = Db::table('user_address')
		->where('id',$id)
		->update($param);
		if($res){
			return $this->returnJson(200,'操作成功',$res);
		}else{
			return $this->returnJson(400,'操作失败',[]);
		}
	}else{
		// 添加
		$param['user_id'] = $user_id;
		$param['add_time'] = date("Y-m-d H:i:s");
		$param['update_time'] = date("Y-m-d H:i:s");
		$res = Db::table('user_address')
		->insert($param);
		if($res){
			return $this->returnJson(200,'操作成功',$res);
		}else{
			return $this->returnJson(400,'操作失败',[]);
		}
	}
  }
  // 设置默认配送地址
  public function setDefaultDeliveryAddress()
  {
	$param = Request::param();
	$id = $param['id'];
	$user_id = $this->getUserId();
		
	// 把所有的user_id下的 default 字段 改成0 把id 为$id的改为1 这种操作用不用加事务 
	Db::startTrans();
	try{
		Db::table('user_address')
		->where('user_id',$user_id)
		->update(['default'=>0]);
	
		$res = Db::table('user_address')
		->where('id',$id)
		->update(['default'=>1]);
		if($res){
			Db::commit();
			return $this->returnJson(200,'操作成功',[]);
		}else{
			Db::rollback();
			return $this->returnJson(400,'操作失败1',[]);
		}
		
	}catch(\Exception $e){
		Db::rollback();
		return $this->returnJson(400,'操作失败3',[]);
	}
  }
  // 删除配送地址
  public function deleteDeliveryAddress()
  {
	$param = Request::param();
	$id = $param['id'];
	$user_id = $this->getUserId();
	// 逻辑删除
	$res = Db::table('user_address')
	->where('id',$id)
	->where('user_id',$user_id)
	->useSoftDelete('delete_time',time())
    ->delete();
	return $this->returnJson(200,'操作成功',$res);
  }
  // 获取配送地址列表
  public function getDeliveryAddressList()
  {
	$user_id = $this->getUserId();
	$res = Db::table('user_address')
	->where('user_id',$user_id)
	->whereNull('delete_time')
	->select();
	return $this->returnJson(200,'操作成功',$res);
  }
  // 获取默认配送地址 
  public function getDefaultDeliveryAddress()
  {
	$user_id = $this->getUserId();
	$res = Db::table('user_address')
	->where('user_id',$user_id)
	->where('default',1)
	->whereNull('delete_time')
	->find();
	return $this->returnJson(200,'操作成功',$res);
  }
  // 领取奖励
  public function getReward()
  {
	$param = Request::param();
	$user_id = $this->getUserId();
	$id = $param['aid'];
	$address_id = $param['address_id'];
	

	$aid = Db::table('award_history')
			->where('id',$id)
			->value('aid');
	$award_info = Db::table('award')
		->where('id',$aid)
		->find();
	
   
	

	// 1 加购换本品 2 赠送本品+积分 3 加购换实物+积分 4 赠送实物+积分 5赠送实物 6概率 
	$pay_price = $award_info['pay_price']; // 换购需要支付金额
	$give_points = $award_info['give_points']; // 赠送用户积分
	$give_hzs_points = $award_info['give_hzs_points']; // 用户得奖赠送合作商积分
	
	 Db::table('award_history')
			->where('id',$id)
			->update(
				['total_amount'=>$pay_price,
				 'give_points'=>$give_points
				,'give_hzs_points'=>$give_hzs_points
		        ]
	        );
	if(!$pay_price || $pay_price=='0.00'){
		if($give_points){
			$dd = [
				'points'=>$give_points,
				'user_id'=>$user_id,
				'add_time'=>date("Y-m-d H:i:s"),
				'update_time'=>date("Y-m-d H:i:s"),
				'type'=>1,
				'order_id'=>$id,
			];
			$res = Db::table('point_water')
			->insert($dd);
		}
		if($give_hzs_points){
			$qr_sn = Db::table('award_history')
			->where('id',$id)
			->value('qr_sn');
			$hzs_user_id = Db::table('write_off_history')
					->where('qr_sn',$qr_sn)
					->where('role',2)
					->value('user_id');
			if($hzs_user_id){
				$dd = [
					'points'=>$give_hzs_points,
					'user_id'=>$hzs_user_id,
					'add_time'=>date("Y-m-d H:i:s"),
					'update_time'=>date("Y-m-d H:i:s"),
					'type'=>1,
					'order_id'=>$id,
				];
				$res = Db::table('point_water_hzs')
				->insert($dd);
			}
		}
		//修改 award_history 表 把type 改为1 并且 写入 address_id
		$res = Db::table('award_history')
		->where('id',$id)
		->update([
			'address_id'=>$address_id,
			'status'=>1,
		]);
	}else{
		$res = Db::table('award_history')
		->where('id',$id)
		->update([
			'address_id'=>$address_id
		]);
	}
	return $this->returnJson(200,'操作成功',['id'=>$id]);
  }
  // 奖励支付
  public function awardPay()
  {
	$param = Request::param();
	$user_id = $this->getUserId();
	$id = $param['id'];
	$address_id = $param['address_id'];
	
	Db::table('award_history')
	->where('id',$id)
	->update([
		'address_id'=>$address_id,
	]);
	
	$pay_info = Db::table('award_history')
			->where('id',$id)
			->find();
	$pay_price = $pay_info['total_amount'];
	if($pay_price && $pay_price!='0.00'){
		// 加购换本品 或 加购换实物+积分
		$total_amount = $pay_price;
		$order_sn = createOrderSn();
		$user_info = Db::table('users')
								->field('openid')
								->where('id',$user_id)
								->find();
		
		$app = $this->getEasyWeChatPayment();
		
		
		$domain = $this->domain;
		
	    $pay_data = [
				'body'=> '购买商品',
				'out_trade_no'=>$order_sn,
				// 'total_fee'=> $total_amount*100,
				'total_fee'=> 1,
				'notify_url'=>$domain.'/api/awardNotic',
				'trade_type'=> 'JSAPI',
				'openid'=>$user_info['openid'],
	    ];
		    //  o1aiq7Qb0Xs_0kxsW7mjZgpGMPLg
		$result = $app->order->unify($pay_data);
		     
		 if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
					// 组装数据返回小程序
					$sign_param = [
						'appId' => $result['appid'],
						'nonceStr' => uniqid(),
						'package' => 'prepay_id=' . $result['prepay_id'],
						'signType' => 'MD5',
						'timeStamp' => time().''
					];
					$sign_param['paySign'] = Support\generate_sign($sign_param, $app->config->key, $sign_param['signType']);
					unset($sign_param['appId']);
					
				   return $this->returnJson(200,'',$sign_param);
		  }
	}
  }
  // 奖励通知
  public function awardNotic()
  {
	$app = $this->getEasyWeChatPayment();
		$response = $app->handlePaidNotify(function ($message, $fail) {
			// Log::channel('pay')->info($message);
			$order_info = Db::table('award_history')
									->where('order_sn',$message['out_trade_no'])
									->find();
			if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
				Db::startTrans();
				try {
					if($order_info['status']==0){
    					Db::table('award_history')
    						->where('order_sn', $order_info['order_sn'])
    						->update([
    						        'status'=>1,
    						        'pay_time'=>date("Y-m-d H:i:s"),
    						   ]);
						$give_points = $order_info['give_points']; // 赠送用户积分
						$give_hzs_points = $order_info['give_hzs_points']; // 用户得奖赠送合作商积分
						if($give_points){
								$dd = [
									'points'=>$give_points,
									'user_id'=>$order_info['uid'],
									'add_time'=>date("Y-m-d H:i:s"),
									'update_time'=>date("Y-m-d H:i:s"),
									'type'=>1,
									'order_id'=>$order_info['id'],
								];
								$res = Db::table('points_water')
								->insert($dd);
		                }
						if($give_hzs_points){
							$qr_sn = $order_info['qr_sn'];
							$hzs_user_id = Db::table('write_off_history')
									->where('qr_sn',$qr_sn)
									->where('role',2)
									->value('user_id');
							if($hzs_user_id){
								$dd = [
									'points'=>$give_hzs_points,
									'user_id'=>$hzs_user_id,
									'add_time'=>date("Y-m-d H:i:s"),
									'update_time'=>date("Y-m-d H:i:s"),
									'type'=>1,
									'order_id'=>$order_info['id'],
								];
								$res = Db::table('point_water_hzs')
								->insert($dd);
							}
						}
					}
					
					// 提交事务
					Db::commit();
				} catch (\Exception $e) {
					//回滚事务
					Db::rollback();
				}
			
			}
		});
  }
  // 获取领取奖励详情 
  public function getRewardDetail()
  {
	$param = Request::param();
	$id = $param['id'];
	$res = Db::table('award_history')
	->where('id',$id)
	->find();
	$address_id = $res['address_id'];
	$aid = $res['aid'];

	$res['address_info'] = Db::table('user_address')
	->where('id',$address_id)
	->find();
	$res['award_info'] = Db::table('award')
	->where('id',$aid)
	->find();

	return $this->returnJson(200,'操作成功',$res);
  }
  // 获取我的中奖记录 
  public function getRewardList()
  {
	$user_id = $this->getUserId();
	$res = Db::table('award_history')
	->where('uid',$user_id)
	->whereNull('delete_time')
	->select()
	->all();
	foreach($res as $k=>$v){
		$res[$k]['award_name'] = Db::table('award')
		->where('id',$v['aid'])
		->value('name');
	}
	return $this->returnJson(200,'操作成功',$res);
  }
  // 获取商品列表
  public function getGoodsList()
  {
	  $res = Db::table('goods')
	  ->whereNull('delete_time')
	  ->select()
	  ->all();
	  return $this->returnJson(200,'操作成功',$res);
  }
  // 获取商品详情 
  public function getGoodsDetail()
  {
	$param = Request::param();
	$id = $param['id'];
	$res = Db::table('goods')
	->where('id',$id)
	->find();
	return $this->returnJson(200,'操作成功',$res);
  }
  // 获取积分兑换明细
  public function getPointExchangeDetail()
  {
	$param = Request::param();
	$page=$param['page'];
	$pageSize = $param['pageSize'];
	$page=($page-1)*$pageSize;
	$user_id = $this->getUserId();

	// 获取用户角色
	$role = Db::table('users')
	->where('id',$user_id)
	->value('role');
	$table_name = 'point_water';
	if($role==1){
		$table_name = 'points_water';
	}else if($role==2){
		$table_name = 'point_water_hzs';
	}

	$res = Db::table($table_name)
	->where('type',2)
	->where('user_id',$user_id)
	->order('id','desc')
	->limit($page,$pageSize)
	->whereNull('delete_time')
	->select()
	->all();
	foreach($res as $k=>$v){
		$res[$k]['goods_name'] = Db::table('goods')
		->where('id',$v['goods_id'])
		->value('goods_name');
	}
	return $this->returnJson(200,'操作成功',$res);
  }
  // 查询省份数据
	public function lodeProvince()
	{
		  $param = Request::param();
		  $result = Db::table('t_address_province')
		             ->select();
        return $this->returnJson(200,'操作成功',$result);
		  
	}
	// 查询城市数据
	public function lodeCity()
	{
		  $param = Request::param();
          $provinceCode = $param['provinceCode'];
		  $result = Db::table('t_address_city')
                     ->where('provinceCode',$param['provinceCode'])
		             ->select();
        return $this->returnJson(200,'操作成功',$result);
		  
	}
    // 查询区域数据
    public function lodeTown()
	{
		  $param = Request::param();
          $cityCode = $param['cityCode'];
		  $result = Db::table('t_address_town')
                     ->where('cityCode',$param['cityCode'])
		             ->select();
        return $this->returnJson(200,'操作成功',$result);
		  
	}
	// 订单状态数量
	public function getOrderStatus()
	{
		$param = Request::param();
		
		$user_id = $this->getUserId();
		
		//待支付
		$count1 = Db::table('order_info')
		->where('user_id',$user_id)
		->where('status','1')
		->whereNull('delete_time')
		->count();
		
		// 已支付未配送
		$count2 = Db::table('order_info')
		->where('user_id',$user_id)
		->where('status','2')
		->whereNull('delete_time')
		->count();
		
		// 
		$count3 = Db::table('order_info')
		->where('user_id',$user_id)
		->where('status','3')
		->whereNull('delete_time')
		->count();
	    
	    $count4 = Db::table('order_info')
		->where('user_id',$user_id)
		->where('status','4')
		->whereNull('delete_time')
		->count();
		
		$dd = [
			'count1'=>$count1,
			'count2'=>$count2,
			'count3'=>$count3,
			'count4'=>$count4,
		];
		return $this->returnJson(200,'操作成功',$dd);

	}
	// 确认收货
	public function confirmReceive()
	{
		$param = Request::param();
		$id = $param['id'];
		$res = Db::table('order_info')
		->where('id',$id)
		->update([
			'status'=>4,
		]);
		if($res){
			return $this->returnJson(200,'操作成功',['id'=>$id]);
		}else{
			return $this->returnJson(400,'操作失败',[]);
		}
	}
	// 自动确认收货
	public function autoConfirmReceive()
	{
		//查询出订单表add_time status=3 超出10天的 自动确认收货
		$time = date('Y-m-d H:i:s',strtotime('-10 day'));
		$res1 = Db::table('order_info')
		->where('status','3')
		->where('add_time','<',$time)
		->whereNull('delete_time')
		->select()
		->all();
		$res2 = Db::table('award_history')
		->where('status','2')
		->where('add_time','<',$time)
		->whereNull('delete_time')
		->select()
		->all();
		if($res2){
			foreach($res2 as $k2=>$v2){
				Db::table('award_history')
				->where('id',$v2['id'])
				->update([
					'status'=>3,
				]);
			}
		}
		if($res1){
			foreach($res1 as $k1=>$v1){
				Db::table('order_info')
				->where('id',$v1['id'])
				->update([
					'status'=>4,
				]);
			}
		}
		return $this->returnJson(200,'操作成功',[]);
		
	}
}
